package top.frsf.autocodegen.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.frsf.autocodegen.utils.Result;

import java.util.List;

/**
 * 全局异常处理器
 *
 * @author FRSF
 * @since 2024/7/26 16:24
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("全局异常处理器:", e);
        return Result.fail(e.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("全局异常处理器:", e);
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors = result.getAllErrors();
        StringBuilder errorMessage = new StringBuilder();
        for (ObjectError error : errors) {
            FieldError fieldError = (FieldError) error;
            errorMessage.append(fieldError.getField())
                    .append(":")
                    .append(fieldError.getDefaultMessage()).append("; ");
        }
        return Result.fail(errorMessage.toString());
    }
}
